package com.lwei.ljpro.filter;

import com.lwei.ljpro.emun.CookieName;
import com.lwei.ljpro.entry.UserEntry;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

//@Component
//@Order(0)
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        System.out.println("登陆拦截器启动成功");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();

        UserEntry currentUser = (UserEntry) session.getAttribute(CookieName.USER_CURRENT.getValue());
        if(currentUser == null){
            String[] uris = request.getRequestURI().split("/");
            List<String> list = Arrays.asList(uris);
            if(!list.contains("loginCenter") && !list.contains("loginCenterRest")){
                response.sendRedirect("/login");
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
